#!/usr/bin/env python
# -*- coding: UTF-8 -*-

'''
Copyright (C) 2010-2011 dbzhang800@gmail.com
All rights reserved.
'''

try:
    from PySide import QtCore, QtGui
except ImportError:
    import sip
    sip.setapi("QString",  2)
    sip.setapi("QVariant",  2)
    from PyQt4 import QtCore, QtGui
    QtCore.Signal = QtCore.pyqtSignal

import math
import sys
import os.path
from aber import AberResFile

def getResult(filename):
    res = AberResFile(filename)

    M  = res.getMagnification()
    So = res.getSourceSize()
    try:
        Cs = res.getSphericalAber() / 1000.
    except:
        Cs = None
    Ai = res.getAi()
    Ao = res.getAo()
    try:
        Cc = res.getChromaticAB() * 1000.
    except:
        Cc = None
    Dv = res.getBeamVoltageRipple()
    Vi = res.getBeamVoltageAtImage()
    Lambda = res.getLambda()
    GL = res.getMLensExcitation(1)
    OL = res.getMLensExcitation(2)
    
    if M and So and Cs and Cc and Ai and Dv and Vi and Lambda:
        Dg = M*So
        Ds = 0.5*Cs*Ai*Ai*Ai
        Dc = 0.5*Cc*Ai*Dv/Vi
        Dd = 0.75*1.22*Lambda/Ai
        D = math.sqrt(Dg*Dg+Ds*Ds+Dc*Dc+Dd*Dd)
        I = math.pi * 1.215*1e6 * (math.tan(Ai/1000) ** 2)
        depth = 2*D/Ai
    else:
        Dg,  Ds,  Dc,  Dd,  D,  I,  depth = None, None, None, None, None,  None,  None
        
    return [M, GL, OL, Ao, Ai, Cs, Cc, Ds, Dc, Dg, Dd, D, depth, I]

def getHeader():
    return ['M', 'GL', 'OL', 'Ao', 'Ai', 'Cs', 'Cc', 'Ds', 'Dc', 'Dg', 'Dd', 'D', 'depth', 'I']

class TableWidget(QtGui.QTableWidget):
    def __init__(self,  parent=None):
        super(TableWidget, self).__init__(parent)
        self.copyaction = QtGui.QAction("&Copy",  self)
        self.copyaction.setDisabled(True)
        #self.copyaction.setShortcut(QtGui.QKeySequence.Copy)
        self.copyaction.triggered.connect(self.onCopy)
        
        self.itemSelectionChanged.connect(self.onSelectionChanged)
        
    def onSelectionChanged(self):
        self.copyaction.setEnabled(self.selectionModel().hasSelection())
        
    def onCopy(self):
        selectedrange = self.selectedRanges()[0]
        dat = ""
        for i in range(selectedrange.rowCount()):
            if i>0:
                dat += "\n"
            for j in range(selectedrange.columnCount()):
                if j>0:
                    dat += '\t'
                dat += self.item(i, j).text()
        QtGui.qApp.clipboard().setText(dat)
        
    def contextMenuEvent(self, evt):
        menu = QtGui.QMenu()
        menu.addAction(self.copyaction)
        menu.exec_(self.viewport().mapToGlobal(evt.pos()))

class Dialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.readSettings()
        self.nameEdit = QtGui.QLineEdit()
        self.nameEdit.setReadOnly(True)
        self.nameEdit.setAcceptDrops(False)
        self.openButton = QtGui.QPushButton(u"打开")
        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.nameEdit)
        hbox.addWidget(self.openButton)
        
        self.resultEdit = TableWidget()
        self.resultEdit.setAcceptDrops(False)
        self.resultEdit.setColumnCount(len(getHeader()))
        self.resultEdit.setHorizontalHeaderLabels(getHeader())
        mainbox = QtGui.QVBoxLayout(self)
        mainbox.addLayout(hbox)
        mainbox.addWidget(self.resultEdit)
        #mainbox.addStretch()
        
        self.openButton.clicked.connect(self.onOpenButtonClicked)
        self.setAcceptDrops(True)
        self.setWindowTitle(u"提取res文件数据")
        
    def onOpenButtonClicked(self):
        path = QtGui.QFileDialog.getOpenFileName(self,  u"选择aber的结果文件",  self.lastpath,  "aber res(*.res)")
        if isinstance(path,  tuple): #pyside return a tuple
            path = path[0]
        if path:
            self.doLoadFile(path)
            
    def doLoadFile(self, path):
            self.lastpath = path
            self.nameEdit.setText(path)

            resultlist = getResult(path)
            self.resultEdit.insertRow(0)
            indices = xrange(sys.maxint)
            for it, idx in zip(resultlist, indices):
                item = QtGui.QTableWidgetItem(str(it))
                self.resultEdit.setItem(0, idx, item)
            self.resultEdit.setVerticalHeaderItem(0, QtGui.QTableWidgetItem(os.path.basename(path)))
            
    def dragEnterEvent(self, evt):
        if evt.mimeData().hasUrls():
            evt.acceptProposedAction()
            
    def dropEvent(self, evt):
            if evt.mimeData().hasUrls():
                path = evt.mimeData().urls()[0].toLocalFile()
                if path.endswith(".res"):
                    self.doLoadFile(path)
            evt.accept()
                    
    def closeEvent(self, evt):
        self.writeSettings()
        
    def readSettings(self):
        settings = QtCore.QSettings()
        self.lastpath = settings.value("lastPath", "")
        self.restoreGeometry(settings.value("geometry",  QtCore.QByteArray()))
        settings.beginGroup("res")
        settings.endGroup()
        
    def writeSettings(self):
        settings=QtCore.QSettings()
        settings.setValue("lastPath", self.lastpath)
        settings.setValue("geometry",  self.saveGeometry())
        settings.beginGroup("res")
        settings.endGroup()

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    app.setOrganizationName(u"HMICN")
    app.setOrganizationDomain(u"")
    app.setApplicationName(u"Res for LiShuai2")
    app.setApplicationVersion(u"0.9.0.0")
    QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)
    w = Dialog()
    w.show()
    sys.exit(app.exec_())
